package cn.gok.tech.baiduocr.controller;

import cn.gok.tech.baiduocr.entity.FileUtil;
import cn.gok.tech.baiduocr.entity.ReturnData;
import cn.gok.tech.baiduocr.service.OperationService;
import com.alibaba.fastjson.JSON;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UploadController {


    @Autowired
    private OperationService operationService;

    //跳转到上传文件的页面
    @RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
    public String goUploadImg() {
        //跳转到 templates 目录下的 uploadimg.html
        return "uploadimg";
    }

    //处理文件上传
    @RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
    @ResponseBody
    public  String uploadImg(@RequestParam MultipartFile file,
                     HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        System.out.println("fileName-->" + fileName);
//        System.out.println("getContentType-->" + contentType);
        //存放文件的目录  放到服务器目录下
        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
//        System.out.println(filePath);
//        String path=request.getServletContext().getRealPath("imgupload");
//        System.out.println(path+"*************");

        //把图片绝对路径放到作业域
//        request.setAttribute("imgpath", filePath+fileName);
        String imagePath=filePath+fileName;
        //获取文字识别json数据
//        String fontOCR = operationService.fontOCR(imagePath);
        //放到Map集合
//        Map map=new HashMap();
//        map.put("code",0);
//        map.put("fontocr",fontOCR);
//        map.put("imagePath", imagePath);
//        map.put()
        //数据放到对象
        ReturnData data=new ReturnData();
        data.setCode(0);
//        data.setFontocr(fontOCR);
//        data.setImagePath(imagePath);
        data.setData(imagePath);

        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);

        } catch (Exception e) {
          e.printStackTrace();
        }

        //返回json
        String str=JSON.toJSONString(data);
//        System.out.println(str);

        return str;
    }

}
